import { Component } from '@angular/core';
import { IonicPage, ToastController } from 'ionic-angular';
import ECharts from 'echarts';
import { HttphandleProvider } from '../../providers/httphandle/httphandle';
import { LocalstorageProvider } from '../../providers/localstorage/localstorage';
import { Tools } from '../../tools/tools';
import { Router } from '@angular/router';
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Network } from '@ionic-native/network';

/**
 * Generated class for the AnnualStatisticsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
interface lineType {  // 产线数据类型
  productionLineId: string;
  productionLineName: string;
  productionLineNumber?: string;
}

@IonicPage()
@Component({
  selector: 'page-annual-statistics',
  templateUrl: 'annual-statistics.html',
})

export class AnnualStatisticsPage extends Tools{
  // private title: string = '年度统计';
  private prolist:any = [];
  private temp:number = -1;
  private selectedLine:lineType;  // 当前展示的产线信息，默认是总体
  private lines:Array<lineType>;  // 请求到的所有可选产线
  private topInfo:any = {
    firstPassPercent: '',
    operationRate: ''
  }
  private topPieTitle:string = '';
  private currentYear:number;  // 当前年度
  private showTopPie: boolean = false;
  private errMsg:string = '';
  constructor(
    private loc: LocalstorageProvider,
    private http: HttphandleProvider,
    private toastCtrl: ToastController,
    protected route: Router,
    protected nativePageTransitions: NativePageTransitions,
    protected network: Network
  ) {
    super(route, nativePageTransitions, network)
    if (!this.selectedLine) {
      this.selectedLine = {
        productionLineId: '',
        productionLineName: '总体'
      }
    }
    this.currentYear = new Date().getFullYear()
    if(this.getNetworkInfo){
      this.requestGetLine(() => {
        this.requestGetStatisticsInfoByYear()
      })
    } else{
      this.toastCtrl.create({
        message: '网络不可用',
        position: 'top',
        duration: 1000
      }).present();
    }
  }

  back(){
    this.openPage('productStatistics')
  }
  doRefresh(refresher){
    // 下拉加载
    this.requestGetStatisticsInfoByYear(refresher)
  }

  changeline(){
    this.requestGetStatisticsInfoByYear()
  }

  showAccordion(index) {
    if (index == this.temp) {
      this.temp = -1
    }else {
      this.temp=index;
    }
  }

  createTopPie(obj){
    var toppie = ECharts.init(document.getElementById('toppie') as HTMLDivElement);
    var option = {
      title: {
        text: obj.count,
        subtext: '总产量(件)',
        left: 'center',
        top: '35%',
        textStyle: {
          fontSize: 24
        },
        subtextStyle: {
          fontSize: 18
        }
      },
      color:['#f2b447','#d75643','#7db6f2','#79c89d'],
      series: [{
        name:'生产统计',
        type:'pie',
        radius: ['50%', '70%'],
        center : ['50%', '42%'],
        avoidLabelOverlap: false,
        hoverAnimation: false,
        label : {
          normal : {
            formatter: '{b}\n{d}%',
          }
        },
        data:obj.productsCountRate
      }]
    };
    toppie.setOption(option)
  }

  createOptions(title,arr){

    function handlelengend(name,arr){
      var res = ''
      for(var i = 0; i < arr.length; i ++) {
        if(arr[i]['name'] == name) {
          if (name.length >= 8 ) {
            name = name.slice(0,8) + '\n' + name.slice(8)
          }
          res = name + ' (' + arr[i]['value'] + ')'
        }
      }
      return res
    }

    var baseOptions = {
      title : {
        text: '',
        x:'center',
        top: '10',
        textStyle: {
          fontWeight: "normal"
        }
      },
      color:['#3557be','#3588d9','#93d9e1','#aad48b','#fee181','#e4ac49'],
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 15,
        top: 60,
        bottom: 20,
        formatter(name){
          return handlelengend(name,arr)
        },
        data: [],
      },
      series : [{
        name:'半径模式',
        type:'pie',
        radius : [40, 80],
        center : ['28%', '45%'],
        hoverAnimation: false,
        labelLine:{
          normal: {
            length: 15,
            length2: 10
          }
        },
        label: {
          normal: {
            show: false,
            fontSize: 14,
            formatter: function(val){
              var originalName = val.name
              if (originalName.length >= 6 ) {
                originalName = originalName.slice(0,6) + '\n' + originalName.slice(6)
              }
              return `${originalName}\n(${val.value})`
            }
          }
        },
        data:[]
      }]
    };
    baseOptions.title.text = title + '缺陷分布'
    baseOptions.series[0].data = arr;
    for (var j = 0; j < arr.length; j ++) {
      baseOptions.legend.data.push(arr[j]['name'])
    }
    return baseOptions
  }

  createPieCharts() {
    for (let i = 0, ilen = this.prolist.length; i < ilen; i++) {
      if (this.prolist[i].defectInfo.length > 0) {
        var pie = ECharts.init(document.getElementById('pie'+i) as HTMLDivElement);
        var option = this.createOptions(this.prolist[i]['productTypeName'],this.prolist[i].defectInfo)
        pie.setOption(option)
      }
    }
  }

  requestGetLine(fn,refresher?){
    this.http.get('/app/rest/v2/services/yes_ProductionStatisticsService/getProductionLinesInfo')
      .then(res => {
        if (res.length > 0) {
          this.lines = res
          this.lines.splice(0, 0, {
            "productionLineName": "总体",
            "productionLineId": "",
            "productionLineNumber": "总体"
          });
          fn && fn()
        } else {
          this.errMsg = '您尚未有任何产线'
        }
        refresher && refresher.complete()
      }).catch(err => {
      refresher && refresher.complete()
      if (err.status === 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetLine(fn)
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();
        console.log("服务器或网络", err)
      }
    })
  }

  requestGetStatisticsInfoByYear(refresher?){
    if (!this.lines || this.lines.length == 0) {
      this.requestGetLine(() => {
        this.requestGetStatisticsInfoByYear()
      },refresher)
      return false
    }
    console.log('请求年度统计');
    this.http.get('/app/rest/v2/services/yes_ProductionStatisticsService/getStatisticsInfoByYear',{
      productionLineId: this.selectedLine.productionLineId,
      year: this.currentYear
    }).then(res => {
      this.topInfo.firstPassPercent = res.firstPassPercent
      this.topInfo.operationRate = res.operationRate
      this.prolist = res.productTypeInfo
      this.topPieTitle = `${this.currentYear} ${this.selectedLine.productionLineName}生产情况`
      refresher && refresher.complete()
      if (res.productsCountRate.length > 0) {
        this.showTopPie = true
      } else {
        this.showTopPie = false
      }
      setTimeout(() => {
        if (res.productsCountRate.length > 0) {
          this.createTopPie(res)
        }
        this.createPieCharts()
      },100)
    }).catch(err => {
      if (err.status == 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetStatisticsInfoByYear(refresher)
        })
      } else {
        this.prolist = []
        this.showTopPie = false
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();
        refresher && refresher.complete()
        console.log("服务器或网络", err)
      }
    })
  }
}
